#include    "dc_motor.h"
#include    "STC8G_H_GPIO.h"
#include    "STC8G_PCA.h"

#define PCAx        PCA1
#define PCA_PWMx    PCA_PWM1

__code u8 clkdiv[6] = {PCA_Clock_1T, PCA_Clock_2T, PCA_Clock_4T,
                       PCA_Clock_6T, PCA_Clock_8T, PCA_Clock_12T};

void SetPWMFreq(PWM_Freq freq)
{
    if((u8)freq<3){
        CMOD = (CMOD  & ~(7<<1)) | PCA_Clock_1T;
        PCA_PWMx  = (PCA_PWMx & ~(3<<6)) | (2-freq)<<1;
    }else if((u8)freq==3){
        CMOD = (CMOD  & ~(7<<1)) | PCA_Clock_2T;
        PCA_PWMx  = (PCA_PWMx & ~(3<<6)) | PCA_PWM_8bit;
    }else{
        CMOD = (CMOD  & ~(7<<1)) | clkdiv[freq-4];
        PCA_PWMx  = (PCA_PWMx & ~(3<<6)) | PCA_PWM_10bit;
    }
}

void SetMotor1024(u16 duty1024)
{
    duty1024 = 1024 - duty1024;
    u8 EBS = PCA_PWMx>>6;
    if(EBS != 3){
        duty1024 >>= EBS+2;
    }
    UpdatePcaPwm(PCAx, duty1024);
}
